<template>
  <div class="classJur">
    <!-- <commonHeader>用户权限管理</commonHeader> -->
    <el-button type="primary" @click="dialogVisible2 = true" class="elntn"
      >添加新用户</el-button
    >
    <el-table border :data="tableData" style="width: 100%">
      <el-table-column align="center" fixed prop="username" label="昵称">
      </el-table-column>
      <el-table-column align="center" fixed prop="shengfen1" label="身份">
      </el-table-column>
      <el-table-column align="center" fixed prop="email" label="邮箱">
      </el-table-column>

      <el-table-column align="center" fixed="right" label="路由权限">
        <template slot-scope="scope" v-if="scope.row.shengfen != 2">
          <el-button @click="handleClick(scope.row)" type="text" size="small"
            >编辑</el-button
          >
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="用户信息">
        <template slot-scope="scope" v-if="scope.row.shengfen != 2">
          <el-button @click="handleClick1(scope.row)" type="text" size="small"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-show="isPageShow"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 8, 10, 20]"
      :page-size="8"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 筛选相关权限 -->
    <el-dialog label="分配权限" :visible.sync="dialogVisible" width="30%">
      <el-tree
        ref="tree"
        :data="jurlist"
        show-checkbox
        node-key="id"
        @check-change="handleCheckChange"
        :default-expanded-keys="[2, 3]"
        :default-checked-keys="arr"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="hadleDialogVisible">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息 -->
    <el-dialog label="用户信息" :visible.sync="dialogVisible1" width="30%">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户呢称" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input disabled="true" v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="修改密码" prop="password1">
          <el-input
            placeholder="不填，表示不修改密码"
            type="password1"
            v-model="ruleForm.password1"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份" prop="shengfen">
          <el-select v-model="ruleForm.shengfen1" placeholder="请选择用户身份">
            <el-option label="学生" value="0"></el-option>
            <el-option label="老师" value="1"></el-option>
            <el-option label="管理员" value="2"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >立即修改</el-button
          >
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 添加新用户信息 -->
    <el-dialog label="用户信息" :visible.sync="dialogVisible2" width="30%">
      <el-form
        :model="ruleForm2"
        :rules="rules1"
        ref="ruleForm2"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户邮箱" prop="email">
          <el-input type="email" v-model="ruleForm2.email"></el-input>
        </el-form-item>
           <el-form-item label="用户学号" prop="xuehao">
          <el-input v-model="ruleForm2.xuehao"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="ruleForm2.password"></el-input>
        </el-form-item>
        <el-form-item label="身份" prop="shengfen">
          <el-select v-model="ruleForm2.shengfen" placeholder="请选择用户身份">
            <el-option label="学生" value="0"></el-option>
            <el-option label="老师" value="1"></el-option>
            <el-option label="管理员" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm1('ruleForm2')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import commonHeader from "@/components/common/commonHeader.vue";
const commonHeader = () => import("@/components/common/commonHeader.vue");
import {
  getUsers,
  updataUserJur,
  updataUserData,
  adminRegisterUser,
} from "@/api/data";
import { handleJur, delArr, sleep } from "@/tool";

export default {
  data() {
    return {
      ruleForm2: {
        email: "",
        xuehao:'',
        password: "",
        shengfen: "",
      },
      timer: null,
      selectUser: null,
      shengfen: "",
      updataJurList: [],
      arr: [],
      jurlist: [],
      currentPage: 1, // 当前页
      pageSize: 8, // 每页多少条
      total: 0,
      defaultProps: {
        children: "children",
        label: "label",
      },

      dialogVisible: false,
      dialogVisible1: false,
      dialogVisible2: false,
      tableData: [],
      user_id: "",

      ruleForm: {
        username: "",
        password1: "",
        email: "",
        date2: "",
        shengfen: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        shengfen: [
          { required: true, message: "请选择身份", trigger: "change" },
        ],
      },
      rules1: {
        email: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "长度在 5到 20 个字符",
            trigger: "blur",
          },
        ],
          xuehao: [
          { required: true, message: "请输入学号", trigger: "blur" },
          {
            min: 9,
            max: 9,
            message: "长度为9个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "长度在 5 到 20 个字符",
            trigger: "blur",
          },
        ],
        shengfen: [
          { required: true, message: "请选择身份", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.handleChange();
  },
  computed: {
    isPageShow() {
      return this.total > this.pageSize;
    },
  },
  beforeDestroy() {
    clearTimeout(this.timer);
  },
  methods: {
    //提交新建一个用户信息
    submitForm1(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // console.log(this.ruleForm2);
          this.ruleForm2.admin_id = this.$store.state.userdata._id;
          let data = await adminRegisterUser(this.ruleForm2);
          // console.log(data);
          if (data.code == 200) {
            this.$message.success(data.msg);
          }
          this.dialogVisible2=false
        } else {
          this.$message.error("修改失败请重试");
          return false;
        }

        this.dialogVisible1 = false;
      });
    },

    // 提交修改用户信息
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // console.log(this.ruleForm);
          let data = await updataUserData(this.ruleForm);
          this.$message.success(data.msg);
          this.handleChange();
        } else {
          this.$message.error("修改失败请重试");
          return false;
        }

        this.dialogVisible1 = false;
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.handleChange();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.handleChange();
    },

    // 修改用户基本信息
    handleClick1(row) {
      this.ruleForm = JSON.parse(JSON.stringify(row));
      // console.log(this.ruleForm)
      this.selectUser = row;
      this.dialogVisible1 = true;
      // 获取最新的该用户信息
    },

    // 获取用户
    async handleChange() {
      let data = await getUsers({
        _id: this.$store.state.userdata._id,
        num: this.currentPage,
        pageSize: this.pageSize,
      });
      this.total = data.total;
      // 对数据进行处理
      data.data.forEach((item) => {
        if (item.shengfen == 0) {
          item.shengfen1 = "学生";
        } else if (item.shengfen == 1) {
          item.shengfen1 = "老师";
        } else if (item.shengfen == 2) {
          item.shengfen1 = "管理员";
        }
      });
      this.tableData = data.data;
    },

    // 获取选中的数据的数组
    handleCheckChange() {
      let res = this.$refs.tree.getCheckedNodes();
      let arr = [];
      res.forEach((item) => {
        arr.push(item.id);
      });
      this.updataJurList = delArr(arr);
    },

    // 确认修改权限
    async hadleDialogVisible() {
      let data = await updataUserJur({
        admin_id: this.$store.state.userdata._id,
        user_id: this.user_id,
        arr: this.updataJurList,
      });
      this.$message.success(data.msg);
      this.dialogVisible = false;
      this.handleChange();
    },

    // 点击编辑事件
    async handleClick(row) {
      this.jurlist = [];
      this.$nextTick(() => {
        this.user_id = row._id;
        this.dialogVisible = true;
        let { menulist, arr } = handleJur(row.user_jurisdiction_routerlist[0]);
        this.jurlist = menulist;
        this.arr = arr;
      });
    },

    // 延时函数
    sleep(num = 200) {
      clearTimeout(this.timer);
      return new Promise((res) => {
        this.timer = setTimeout(() => {
          res();
        }, num);
      });
    },
  },
  components: {
    commonHeader,
  },
};
</script>

<style>
.classJur {
  padding: 20px;
}

.elntn {
  margin-bottom: 20px;
}
</style>